/*
 * Principal.java
 *
 * Created on 18 de Janeiro de 2010, 16:18
 */

package calpi.gui;

import calpi.Aluno;
import calpi.Connectors;
import calpi.Curso;
import calpi.Disciplina;
import calpi.database.AlunosConnector;
import calpi.database.CursosConnector;
import calpi.database.DisciplinasConnector;
import calpi.util.Comparadores;
import javax.swing.JDialog;
import static javax.swing.JOptionPane.*;

/**
 *
 * @author  sidneyp
 *
 */
public class Principal extends javax.swing.JFrame {

    /** Creates new form Principal */
    public Principal() {

        initComponents();
        try {

            refresh();
        } catch (Exception e) {

            System.err.println(e);
            showMessageDialog(this, "Houve um erro ao acessar os bancos de dados",
                                "ERROR", ERROR_MESSAGE);
        }
    }

    public void refresh() {

        AlunosConnector ac = (AlunosConnector) Connectors
                                    .getConnector(Connectors.ALUNOS);
        ac.setComparator(Comparadores.ComparaAluno.NOME);
        ac.sortBufferOut();
        Object[] alunos = ac.getBufferOut();
        if (alunos == null) {

            return;
        }
        Object[] nomes = new Object[alunos.length];
        for (int a = 0; a < alunos.length; a++) {

            nomes[a] = ((Aluno) alunos[a]).getNome();
        }

        listAlunos.setListData(nomes);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listAlunos = new javax.swing.JList();
        editar = new javax.swing.JButton();
        excluir = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        cadasAluno = new javax.swing.JMenuItem();
        cadasDisci = new javax.swing.JMenuItem();
        cadasCurso = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        consultDisc = new javax.swing.JMenuItem();
        consultCurso = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("CalpI - Cadastro de Alunos");
        setAlwaysOnTop(true);
        setLocationByPlatform(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Alunos Cadastrados");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 10, 292, -1));

        listAlunos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(listAlunos);

        jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 370, 190));

        editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gtk-edit.png"))); // NOI18N
        editar.setText("Editar");
        editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editarActionPerformed(evt);
            }
        });
        jPanel1.add(editar, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 240, -1, -1));

        excluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gtk-delete.png"))); // NOI18N
        excluir.setText("Excluir");
        excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                excluirActionPerformed(evt);
            }
        });
        jPanel1.add(excluir, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 240, -1, -1));

        jMenu1.setText("Cadastro");

        cadasAluno.setText("Aluno");
        cadasAluno.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadasAlunoActionPerformed(evt);
            }
        });
        jMenu1.add(cadasAluno);

        cadasDisci.setText("Disciplina");
        cadasDisci.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadasDisciActionPerformed(evt);
            }
        });
        jMenu1.add(cadasDisci);

        cadasCurso.setText("Curso");
        cadasCurso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadasCursoActionPerformed(evt);
            }
        });
        jMenu1.add(cadasCurso);

        jMenuBar1.add(jMenu1);

        jMenu3.setText("Consultar");

        consultDisc.setText("Disciplina");
        consultDisc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultDiscActionPerformed(evt);
            }
        });
        jMenu3.add(consultDisc);

        consultCurso.setText("Curso");
        consultCurso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultCursoActionPerformed(evt);
            }
        });
        jMenu3.add(consultCurso);

        jMenuBar1.add(jMenu3);

        jMenu2.setText("Sobre");
        jMenu2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu2MouseClicked(evt);
            }
        });
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_excluirActionPerformed

        int selected = listAlunos.getSelectedIndex();
        if (selected == -1) {

            return;
        }
        
        if (showConfirmDialog(this, "Deseja mesmo excluir esse aluno?",
                "CalpI - Cadastro de Alunos", YES_NO_OPTION) == NO_OPTION) {

            return;
        }

        AlunosConnector ac = (AlunosConnector) Connectors
                                    .getConnector(Connectors.ALUNOS);
        if (ac != null) {

            try {

                ac.removeElementBufferOut(selected);
                Connectors.askWrite(Connectors.ALUNOS);
                refresh();
            } catch (Exception e) {}
        }
    }//GEN-LAST:event_excluirActionPerformed

    private void cadasAlunoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadasAlunoActionPerformed

        CursosConnector cc = (CursosConnector) Connectors
                .getConnector(Connectors.CURSOS);
        DisciplinasConnector dc = (DisciplinasConnector) Connectors
                    .getConnector(Connectors.DISCIPLINAS);

        boolean error = false;
        Curso[] cursos = cc.getBufferOut();
        if (cursos == null) {

            showMessageDialog(this, "Não há cursos cadastrados até o momento",
                    "CalpI - Cadatros de Clientes", ERROR_MESSAGE);
            error = true;
        }

        Disciplina[] disci = dc.getBufferOut();
        if (disci == null) {

            showMessageDialog(this, "Não há disciplinas cadastradas até o momento",
                    "CalpI - Cadastros de Clientes", ERROR_MESSAGE);
            error = true;
        }

        if (error) {

            return;
        }
        
        //Esconde a janela pai
        setVisible(false);
        dispose();
        CadastroAluno ca = new CadastroAluno(this, cursos, disci);
        ca.setLocationRelativeTo(this);
        ca.setVisible(true);
    }//GEN-LAST:event_cadasAlunoActionPerformed

    private void editarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarActionPerformed

        int selected = listAlunos.getSelectedIndex();
        if (selected != -1) {

            CursosConnector cc = (CursosConnector) Connectors
                .getConnector(Connectors.CURSOS);
            DisciplinasConnector dc = (DisciplinasConnector) Connectors
                    .getConnector(Connectors.DISCIPLINAS);
            try {

                setVisible(false);
                AlunosConnector ac = (AlunosConnector) Connectors
                                    .getConnector(Connectors.ALUNOS);
                ac.setComparator(Comparadores.ComparaAluno.NOME);
                new CadastroAluno(this, ac.getElementAtBufferOut(selected),
                        cc.getBufferOut(), dc.getBufferOut()).setVisible(true);
            } catch (Exception e) {

                //Não faz nada. Só por precaução =}
            }
        }
    }//GEN-LAST:event_editarActionPerformed

    //Cria a janele que será usada para cadastro e edição de cursos e disciplinas
    private void createModalFrame(java.awt.event.ActionEvent evt, byte tipo) {

        TwoFaceFrameCadas itf = new TwoFaceFrameCadas(tipo);
        JDialog d = new JDialog(this, true);
        d.setLocationRelativeTo(this);
        d.add(itf);
        d.setSize(300, 200);
        d.setResizable(false);
        itf.setVisible(true);
        d.setVisible(true);
    }

    private void createFrameConsulta(java.awt.event.ActionEvent evt, byte tipo) {

        if (tipo == TwoFaceFrameConsulta.CURSOS) {

            Curso[] cc = ((CursosConnector) Connectors
                .getConnector(Connectors.CURSOS)).getBufferOut();
            if (cc == null) {

                showMessageDialog(this, "Não há cursos cadastrados até o momento",
                    "CalpI - Cadatros de Clientes", ERROR_MESSAGE);
                return;
            }

        } else if (tipo == TwoFaceFrameConsulta.DISCIPLINAS) {

            Disciplina[] dc = ((DisciplinasConnector) Connectors
                .getConnector(Connectors.DISCIPLINAS)).getBufferOut();
            if (dc == null) {

                showMessageDialog(this, "Não há disciplinas cadastradas até o momento",
                    "CalpI - Cadatros de Clientes", ERROR_MESSAGE);
                return;
            }
        }

        setVisible(false);
        TwoFaceFrameConsulta fc = new TwoFaceFrameConsulta(this, tipo);
        fc.setLocationRelativeTo(this);
        fc.setVisible(true);
    }

    private void cadasDisciActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadasDisciActionPerformed

        createModalFrame(evt, TwoFaceFrameCadas.DISCIPLINA);
    }//GEN-LAST:event_cadasDisciActionPerformed

    private void cadasCursoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadasCursoActionPerformed

        createModalFrame(evt, TwoFaceFrameCadas.CURSO);
    }//GEN-LAST:event_cadasCursoActionPerformed

    private void consultDiscActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultDiscActionPerformed

        createFrameConsulta(evt, TwoFaceFrameConsulta.DISCIPLINAS);
    }//GEN-LAST:event_consultDiscActionPerformed

    private void consultCursoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultCursoActionPerformed

        createFrameConsulta(evt, TwoFaceFrameConsulta.CURSOS);
    }//GEN-LAST:event_consultCursoActionPerformed

    private void jMenu2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu2MouseClicked

        showMessageDialog(this, "CalpI - Cadastro de Alunos para LP1\n\nGrupo:\n"
                + "José Ivan Bezerra Vilarouca Filho\nMarcos Antonio Limeira Segundo\n"
                + "Raul Corrêia Muniz\nSidney Pontes Filho", "CalpI - Cadastro de Alunos",
                INFORMATION_MESSAGE);
    }//GEN-LAST:event_jMenu2MouseClicked

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing


        try {

            System.out.println("Tentando 'flush'...");
            Connectors.writeAll();
            System.out.println("Done!");
            System.out.println("Destroying connectors...");
            Connectors.destroyConnectors();
            System.out.println("Done!");
        } catch (Throwable e) {

            showMessageDialog(this, "Houve um erro na gravação dos arquivos.",
                    "CalpI - Cadastro de Alunos", ERROR_MESSAGE);
            System.err.println(e);
        }
    }//GEN-LAST:event_formWindowClosing

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem cadasAluno;
    private javax.swing.JMenuItem cadasCurso;
    private javax.swing.JMenuItem cadasDisci;
    private javax.swing.JMenuItem consultCurso;
    private javax.swing.JMenuItem consultDisc;
    private javax.swing.JButton editar;
    private javax.swing.JButton excluir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listAlunos;
    // End of variables declaration//GEN-END:variables

}
